package com.wangxiaonan.berry.config;

import com.wangxiaonan.berry.exception.SystemException;
import feign.Feign;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import javax.annotation.Resource;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

/**
 * @Author: wangxiaonan
 * @Date: 2019/7/2
 **/
public class FeignRepositoryFactoryBean<T> implements FactoryBean<T> {

    @Resource
    private Environment env;

    private Class<T> clazz;

    public FeignRepositoryFactoryBean(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public T getObject() throws Exception {
        FeignRepository feignRepository = clazz.getAnnotation(FeignRepository.class);
        String propertyName = feignRepository.uriPropertyName();
        if (StringUtils.isEmpty(propertyName)) {
            throw new SystemException("Feign uriPropertyName is null!");
        }
        String uri = env.getProperty(propertyName, "");
        if (StringUtils.isEmpty(uri)) {
            throw new SystemException("Feign " + propertyName + " not set");
        }
        return Feign.builder().encoder(new GsonEncoder()).decoder(new GsonDecoder()).target(clazz, uri);
    }

    @Override
    public Class<?> getObjectType() {
        return clazz;
    }


}
